package Presenter;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.XML;

import Models.POSProductServingType;

public class POSProductServingTypePresenter {
	public ArrayList<POSProductServingType> tryJSONParseArray(String input){
		ArrayList<POSProductServingType> psts = new ArrayList<POSProductServingType>();
		try{
			JSONObject jsonObj = null;
			jsonObj = XML.toJSONObject(input);
			JSONObject jsonAllObjects = jsonObj.getJSONObject("pOSProductServingTypes");
				if(!jsonAllObjects.isNull("posProductServingType")){
					Object item = jsonAllObjects.get("posProductServingType");
					if(item instanceof JSONArray){
						JSONArray jArray = (JSONArray)item;
						for(int i=0; i < jArray.length(); i++){
							JSONObject jObject = jArray.getJSONObject(i);
							psts.add(createPSTFromJSONObject(jObject));
						}
					} else {
						JSONObject jObject = (JSONObject)item;
						psts.add(createPSTFromJSONObject(jObject));
					}
				}
			return psts;
		} catch(JSONException ex){
			ex.printStackTrace();
		}
		return null;
	}
	
	public POSProductServingType tryJSONParse(String input){
		try{
			JSONObject jsonObj = null;
			jsonObj = XML.toJSONObject(input);
			JSONObject jsonHop = jsonObj.getJSONObject("posProductServingType");
			POSProductServingType pst = createPSTFromJSONObject(jsonHop);
			return pst;
		} catch(JSONException ex){
			ex.printStackTrace();
		}
		return null;
	}
	
	public POSProductServingType createPSTFromJSONObject(JSONObject jsonPST){
		POSProductServingType pst = new POSProductServingType();
		try{
			pst.setId(jsonPST.getInt("id"));
			pst.setCost(jsonPST.getDouble("stCost"));
			//Build Beer
			POSBeerViewPresenter beerPresenter = new POSBeerViewPresenter();
			JSONObject jsonBeer = jsonPST.getJSONObject("servingTypeBeer");
			pst.setBeer(beerPresenter.createBeerFromJSONObject(jsonBeer));
			//Build Glassware
			POSGlassWarePresenter glasswarePresenter = new POSGlassWarePresenter();
			JSONObject jsonGlassware = jsonPST.getJSONObject("glassware");
			pst.setGlassWare(glasswarePresenter.createGlasswareFromJSONObject(jsonGlassware));
			return pst;
		} catch(JSONException ex){
			ex.printStackTrace();
		} catch(Exception ex){
			ex.printStackTrace();
		}
		return null;
	}
	
	public JSONObject createJSON(POSProductServingType item){
		try{
			JSONObject json = new JSONObject();
			json.put("id", item.getId());
			json.put("stCost", item.getCost());
			POSBeerViewPresenter beerPresenter = new POSBeerViewPresenter();
			json.put("servingTypeBeer", beerPresenter.createJSON(item.getBeer()));
			POSGlassWarePresenter glassPresenter = new POSGlassWarePresenter();
			json.put("glassware", glassPresenter.createJSON(item.getGlassWare()));
			return json;
		} catch(JSONException ex){
			ex.printStackTrace();
		}
		return null;
	}
}
